<template>
  <div id="login">
    <el-dialog :visible.sync="isShow" :show-close="false" title="注册页面">
      <div class="title" slot="title">注册页面</div>
      <div class="footer" slot="footer">
        <el-form :model="form" :rules="rules" ref="form" label-width="67px" status-icon>
          <el-form-item label="图像" prop="avatar">
            <el-upload
              width="180px"
              class="avatar-uploader"
              action="http://127.0.0.1/heimamm/public/uploads"
              name="image"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.avatar" :src="avatar" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="昵称" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="图形码" prop="code">
            <el-row>
              <el-col :span="16">
                <el-input v-model="form.code"></el-input>
              </el-col>
              <el-col :span="7" :offset="1">
                <img @click="getcode" class="changeimgs" :src="codeimg" alt />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="验证码" prop="rcode">
            <el-row>
              <el-col :span="16">
                <el-input v-model="form.rcode"></el-input>
              </el-col>
              <el-col :span="7" :offset="1">
                <el-button class="btn" @click="getwords" :disabled="codetime!=3">
                  <span v-if="codetime==3">获取验证码</span>
                  <span v-if="codetime!=3">再次获取验证码({{ codetime }})</span>
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button @click="fail">取消</el-button>
            <el-button type="primary" @click="resigteruer">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import axios from "axios";
import { getCode, resigter } from "@/api/resigter.js";
export default {
  data() {
    return {
      isShow: false,
      codetime: 3,
      userword: "",
      // iscode: true,
      // imageUrl: "",
      // 开始绑定元素
      baseURL: process.env.VUE_APP_URL,
      codeimg: "http://127.0.0.1/heimamm/public/captcha?type=sendsms",
      avatar: "",
      form: {
        username: "", //	是	string	用户名
        phone: "", //	是	string	手机号
        email: "", //	是	string	邮箱
        avatar: "", //	是	string	头像地址
        password: "", //	是	string	密码
        rcode: "", //	是	string	验证码
        code: "",
      },
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change",
          },
          {
            min: 4,
            max: 10,
            message: "昵称字符要在4-10个字符中哦",
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入电话号码",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              let deg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (deg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的电话号码"));
              }
            },
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              let deg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (deg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱地址"));
              }
            },
          },
        ],
        avatar: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "change",
          },
          {
            min: 4,
            max: 12,
            message: "密码长度要在4-12位之间",
            trigger: "change",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入图片验证码",
            trigger: "change",
          },
        ],
        rcode: [
          {
            required: true,
            message: "请输入短信验证码",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.form.avatar = res.data.file_path;
      this.avatar = this.baseURL + "/" + res.data.file_path;
      console.log(res, file);
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/psd";
      const isLt4M = file.size / 1024 / 1024 < 4;
      console.log(file);
      if (!isJPG) {
        this.imageUrl = file.url;
        this.isShow = true;
        this.$message.error("上传头像图片只能是 JPG/PNG/PSD 格式!");
      }
      if (!isLt4M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      if (isJPG && isLt4M) {
        this.$message.success("上传成功");
      }
      return isJPG && isLt4M;
    },
    // 图片验证码
    getcode() {
      this.codeimg = this.baseURL + "/captcha?type=sendsms" + Date.now();
    },

    getwords() {
      // 电话号码和图形验证码的验证
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        if (errorMessage === "") {
          num++;
        }
      });
      // 获取手机验证码
      if (num == 2) {
        getCode({
          code: this.form.code,
          phone: this.form.phone,
        }).then((res) => {
          if (res.data.data.captcha) {
            this.$message.success(res.data.data.captcha + "");
            this.userword = res.data.data.captcha;
            // 因为定时器是一秒之后执行，防止用户在这期间重复点击 提前减去一秒
            this.codetime--;
            let timeID = setInterval(() => {
              this.codetime--;
              // 当倒计时结束后，停止定时器，并且使状态恢复
              if (this.codetime == 0) {
                clearInterval(timeID);
                this.codetime = 3;
              }
            }, 1000);
          } else {
            this.$message.error("获取失败");
          }
        });
      } else {
        this.$message.error("验证不通过");
      }
      // 调用ajax的时候跨域的话不自带cookie这里验证码使用cookie验证验证码
      // 不跨域会自动带上cookie
      // 跨域允许带cookie  withCredentials:布尔值必须在参数下面

      // getCode({
      //   code: this.form.code,
      //   phone: this.form.phone,
      // }).then((res) => {
      // this.$message.success(res.data.data.captcha + "");
      // });
    },
    resigteruer() {
      this.$refs.form.validate((res) => {
        if (res) {
          if (this.form.rcode == this.userword) {
            resigter(this.form).then((res) => {
              console.log(res);
              this.$message.success("成功注册");
            });
            this.isShow = false;
          } else {
            this.$message.error("请填写正确的验证码");
          }

          // this.$refs.form.resetFields();
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    fail() {
      this.isShow = false;
      this.$refs.form.resetFields();
    },
  },
};
</script>

<style lang='less'>
#login {
  .el-dialog {
    width: 600px;
    height: 786px;
  }

  .title {
    width: 100%;
    height: 53px;
    background-color: #03befa;
    color: #fff;
    font-size: 18px;
    text-align: center;
    line-height: 53px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .element.style {
    margin-left: 0;
  }
  .el-dialog__body {
    padding: 14px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }
  .footer {
    text-align: center;

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .changeimgs {
      width: 100%;
      height: 40px;
    }
    .btn {
      width: 100%;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
}
</style>